import { defineStore } from "pinia";
import { getMenuListApi } from "../../api/menu";
import type { RouteRecordRaw } from "vue-router";
import Layout from '@/layout/index.vue'
import Center from '@/layout/center/center.vue'
const modules = import.meta.glob('../../view/**/*.vue')
export const collapseStore = defineStore('collapseStore',{
 
  state: () => {
    return{
       collapse:false,
       menuList:[{
        path:'/dashboard',
        component:'Layout',
        name:'dashboard',
        meta:{
          title:'首页',
          icon:'HomeFilled',
          roles:['sys:dashboard']
        }
       }],
       validRoutes: [] as RouteRecordRaw[] // 新增：存储有效路由
    }
    
  },
  getters:{
    getCollapse(state){
        return state.collapse
    },
    getMenu(state){
      return state.menuList;
    },
    getValidRoutes: (state) => state.validRoutes // 新增：获取有效路由
  },
  actions: {
    setCollapse(collapse:boolean) {
      this.collapse = collapse;
    },
    //获取菜单数据
    getMenuList(router:any,userId:string){
       return new Promise((resolve,reject)=>{
        getMenuListApi(userId).then((res)=>{
          let accessRoute;
          if(res && res.code == 200){
            //生成路由
            accessRoute = generateRoutes(res.data,router) as any
            this.menuList = this.menuList.concat(accessRoute)
          }
          resolve(this.menuList)
        }).catch((error)=>{
          reject(error)
        }
        )
       })
    }
  }
});
export function generateRoutes(routes:RouteRecordRaw[],router:any){
  //路由数据
  const res:Array<RouteRecordRaw> = []
  routes.forEach((route:any)=>{
    const tmp = {...route}
    const component = tmp.component;
    if(route.component){
      if(component == 'Layout'){
         tmp.component = Layout;
      }else{
        const componentPath = `${tmp.component}`;
        const matchedModule = modules[componentPath];
        if (matchedModule) {
          tmp.component = matchedModule;
        } else {
          console.error(`组件未找到: ${componentPath}`);
          return; // 跳过无效路由
        }
      }
    }
    //有下级
    if(tmp.children && tmp.children.length > 0){
       if(route.component != 'Layout'){
        tmp.children = Center;
       }
       //递归
       tmp.children = generateRoutes(tmp.children,router)
    }
    res.push(tmp)
    //加入路由
    router.addRoute(tmp)
    console.log('执行成功')
    console.log('当前路由',router.getRoutes())
  })
  return res;
}